﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMSGSC.BLL;
using PMSGSC.DAL;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraEditors.Controls;
using System.Linq;
using System.Text.RegularExpressions;

namespace PMSGSC.App
{
    public partial class frmEmployee : DevExpress.XtraEditors.XtraForm
    {
        public frmEmployee()
        {
            InitializeComponent();

            employeeBindingSource.DataSource = Employee_BLL.GetAll(frmMain.ship.Ship_ID);
            departmentBindingSource.DataSource = Department_BLL.GetAll(frmMain.ship.Ship_ID);
        }
        // Khai báo trạng thái mặc định 
        private Status status = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private Employee employee = new Employee();
        //Hiển thị số thứ tự của gridview
        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        // Sự kiện cập nhật dữ liệu xuống databse
        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SaveDataToDatabase();
        }
        private void SaveDataToDatabase()
        {
            employee = employeeBindingSource.Current as Employee;
            if (status == Status.Update)
            {
                if (XtraMessageBox.Show("Do you want to save changes?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    bool result = Employee_BLL.Update(employee);

                    if (!result)
                        XtraMessageBox.Show("Update Unsuccess !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else
                        XtraMessageBox.Show("Update Success !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            if (status == Status.New)
            {
                bool result = Employee_BLL.Insert(employee);

                if (!result)
                {
                    XtraMessageBox.Show("Insert Unsuccess!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                status = Status.Update;
            }
            employeeBindingSource.DataSource = Employee_BLL.GetAll(frmMain.ship.Ship_ID);
        }

       
        private void DeleteEmployee(NavigatorButtonClickEventArgs e)
        {
            DeleteEmployeeFinal();
            e.Handled = true;
           
        }

        private void DeleteEmployeeFinal()
        {
            if (XtraMessageBox.Show("Are you sure you want to delete Employee?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                employee = employeeBindingSource.Current as Employee;

                if (Employee_BLL.IsRelationship(employee))
                    Employee_BLL.Delete(employee);
                else
                    XtraMessageBox.Show("Can't Delete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                employeeBindingSource.DataSource = Employee_BLL.GetAll(frmMain.ship.Ship_ID);
            }
        }
        // Sự kiện nhân phím delete sảy ra
        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                DeleteEmployeeFinal();
            }
        }

        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            status = Status.New;
        }

        public static bool isValidEmail(string inputEmail)
        {
            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                  @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                  @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
            Regex re = new Regex(strRegex);
            if (re.IsMatch(inputEmail))
                return (true);
            else
                return (false);
        }  

        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = (GridView)sender;
            GridColumn EmployeeCodeCol = view.Columns["CodeEmployee"];
            GridColumn EmployeeNameCol = view.Columns["NameEmployee"];
            GridColumn DepartmentCol = view.Columns["Department_ID"];

            if (null == gridView1.GetRowCellValue(e.RowHandle, EmployeeCodeCol))
            {
                e.Valid = false;
                view.FocusedColumn = EmployeeCodeCol;
                e.ErrorText = "Please enter the Employee Code.";
                view.SetColumnError(EmployeeCodeCol, "Employee Code cannot be empty");
                return;
            }

            if (null == gridView1.GetRowCellValue(e.RowHandle, EmployeeNameCol))
            {
                e.Valid = false;
                view.FocusedColumn = EmployeeNameCol;
                e.ErrorText = "Please enter the Employee Code.";
                view.SetColumnError(EmployeeNameCol, "Employee Code cannot be empty");
                return;
            }

            if (null == gridView1.GetRowCellValue(e.RowHandle, DepartmentCol))
            {
                e.Valid = false;
                view.FocusedColumn = DepartmentCol;
                e.ErrorText = "Please enter the Department.";
                view.SetColumnError(DepartmentCol, "Department cannot be empty");
                return;
            }

            object Email = gridView1.GetRowCellValue(e.RowHandle, colEmail);
            if (null != Email)
                if (!isValidEmail(Email.ToString()))
                {
                    e.Valid = false;
                    gridView1.FocusedColumn = colEmail;
                    e.ErrorText = "Please enter the Email. ";
                    view.SetColumnError(colEmail, "Email wrong format.");
                    return;
                }

            employee = employeeBindingSource.Current as Employee;
            // kiem tra ma nhan vien
            if (Employee_BLL.IsExits(employee))
            {
                e.Valid = false;
                view.FocusedColumn = gridView1.Columns["CodeEmployee"];
                e.ErrorText = "Employee Code has existed. ";
                view.SetColumnError(EmployeeCodeCol, "Employee Code has existed");
                return;
            }
        }

        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl1.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    employeeBindingSource.DataSource = Employee_BLL.GetAll(frmMain.ship.Ship_ID);
                    status = Status.Update;
                }
            }

        }
        // Đặt lại trạng thái update 
        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                status = Status.Update;
            }
        }

        private void repositoryItemGridLookUpEdit1_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (e.NewValue == null)
                ((Employee)gridView1.GetFocusedRow()).Department = null;
            else
                ((Employee)gridView1.GetFocusedRow()).Department = BaseDAL.DB.Departments.Single(c => c.Department_ID == (int)e.NewValue);
        }

        private void gridControl1_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.Remove:
                    DeleteEmployee(e);
                    break;
            }

        }

        private void txtNumberic_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }
        private static void OnlyInputNumberic(KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }
    }
}